package com.zxx.pattern.observerPattern.observer_bus_reason;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

/**
 * ActivityB 发送广播 A接收
 *
 * @author zxx on 2021/3/11
 */
public class ActivityA extends AppCompatActivity {

    BroadcastReceiver receiver;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                UserA userA = intent.getParcelableExtra("user");

                Log.e("Tag-A->", "-->" + userA.toString());
            }
        };

        registerReceiver(receiver, new IntentFilter("my_action"));

        startActivity(new Intent(this, ActivityB.class));


        new Thread(new Runnable() {
            @Override
            public void run() {
                UserA userA = new UserA("来自子线程");
                Message message = handler.obtainMessage();
                message.what = 1;
                message.obj = userA;

                handler.sendMessage(message);
            }
        }).start();

    }


    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                UserA userA = (UserA) msg.obj;

                Log.e("Tag-接收子线程的消息->", "-->" + userA.toString());
            }
        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
}
